package com.yidu.web.utils;

import com.google.gson.Gson;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.websocket.Session;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class SessionTools {

    /**
     * 用户在线状态
     */
    public static final String STATUS_ON = "1";
    public static final String STATUS_OFF = "0";


    //专门放session的集合
    public static Map<String,Object> SESSIONS = new ConcurrentHashMap<>();


    public static void writerJson(HttpServletResponse response,Object object) throws IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        String json = gson.toJson(object);
        out.print(json);
        out.close();
    }

    /**
     * 上传文件的方法
     * @param part
     * @param request
     * @return
     * @throws IOException
     */
    public static String saveFile(Part part, HttpServletRequest request) throws IOException{

        InputStream is = part.getInputStream();
        ServletContext context = request.getServletContext();
        String realPath = context.getRealPath("/upload");
        String fileName = part.getSubmittedFileName();
        if(fileName==null || "".equals(fileName)){
            return null ;
        }
        int point = fileName.lastIndexOf(".");
        String postfix = fileName.substring(point);
        fileName = UUID.randomUUID().toString()+postfix;
        System.out.println("照片路径："+realPath+"/"+fileName);
        OutputStream os = new FileOutputStream(realPath+"/"+fileName);
        byte b []= new byte[1024];
        int len = 0;
        while((len=is.read(b))>-1){
            os.write(b, 0, len);
        }
        os.close();
        is.close();
        String filePath = "upload/"+fileName;
        return filePath;
    }
}
